package com.bringspring.system.scheduletask.utils;

import com.alibaba.fastjson.JSONObject;
import com.bringspring.common.config.ConfigValueUtil;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.common.util.context.SpringContext;
import com.bringspring.system.base.util.jobutil.JobManager;
import com.bringspring.system.base.util.jobutil.TimeJob;
import com.bringspring.system.scheduletask.entity.TimeTaskEntity;
import com.bringspring.system.scheduletask.model.ContentModel;
import com.bringspring.system.scheduletask.service.TimetaskService;
import org.quartz.CronExpression;
import org.quartz.JobDataMap;

import java.util.List;

public class TaskUtil {

    public static void task() {
        //多租户下不启动任务调度
        ConfigValueUtil configValueUtil = SpringContext.getBean(ConfigValueUtil.class);
        if (!Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
            TimetaskService timetaskService = SpringContext.getBean(TimetaskService.class);
//            DataSourceUtil dataSourceUtil = SpringContext.getBean(DataSourceUtil.class);
//            DblinkService dblinkService = SpringContext.getBean(DblinkService.class);
            List<TimeTaskEntity> list = timetaskService.getList();
            for (TimeTaskEntity entity : list) {
                if (isjson(entity.getExecuteContent())) {
                    ContentModel model = JsonUtil.getJsonToBean(entity.getExecuteContent(), ContentModel.class);
                    JobDataMap jobDataMap = new JobDataMap();
                    jobDataMap.put("content", model);
                    jobDataMap.put("tenantId", "");
                    jobDataMap.put("tenantDbConnectionString", "");
                    jobDataMap.put("id", entity.getId());
                    jobDataMap.put("type", entity.getExecuteType());
                    String jobName = entity.getId();
                    String jobGroupName = "jsbos";
                    String cron = entity.getExecuteCronExpression();
                    if (filterWithCronTime(cron)) {
                        JobManager jobManager = new JobManager();
                        jobManager.addJob(jobName, jobGroupName, cron, jobDataMap, null, null, TimeJob.class);
                    }
                }
            }
        }
    }

    private static Boolean filterWithCronTime(String cron) {
        boolean validExpression = false;
        if (StringUtils.isNotEmpty(cron)) {
            validExpression = CronExpression.isValidExpression(cron);
        }
        return validExpression;
    }

    private static boolean isjson(String string) {
        try {
            JSONObject jsonStr = JSONObject.parseObject(string);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
